package com.base.app_core.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.base.app_core.App;
import com.base.app_core.R;
import com.base.app_core.base.impl.BaseActivity;
import com.base.app_core.ioc.anno.IngoreCopy;
import com.base.app_core.service.user.impl.OnClickListenerForceLogin;
import com.base.app_core.util.glide.GlideUtill;
import com.base.app_core.util.log.F;
import com.blankj.utilcode.util.CloseUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.signature.StringSignature;
import com.tencent.bugly.crashreport.CrashReport;

import com.blankj.utilcode.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;


public class XYBAUtils {

    public static void strongFoucus(View view) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
    }

    /**
     * dip转换px
     */
    public static int dip2px(int dip) {
        final float scale = getResource().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    /**
     * px转换dip
     */

    public static int px2dip(int px) {
        final float scale = getResource().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    public static Resources getResource() {
        return App.getApp().getResources();
    }

    public static Drawable getDrawable(int resId) {
        return getResource().getDrawable(resId);
    }

    public static Context getContext() {
        return App.getContext();
    }


    /**
     * 可以打开activity
     */
    public static void startActivity(Intent intent) {
        // 如果不在activity里去打开activity  需要指定任务栈  需要设置标签
        if (BaseActivity.activity == null) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(intent);
        } else {
            BaseActivity.activity.startActivity(intent);
        }
    }

    /**
     * 读取assets目录下的文本文件
     */
    public static String readFromAsset(String path) {
        InputStream is = null;
        BufferedReader reader = null;
        try {
            is = App.getContext().getAssets().open(path);
            reader = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseUtils.closeIOQuietly(reader);
            CloseUtils.closeIOQuietly(is);
        }
        return null;
    }

    /**
     * 检查是否安装微信
     *
     * @param context
     * @return
     */
    public static boolean checkApkExist(Context context) {
        String packageName = "com.tencent.mm";
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }
    public static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }
    /**
     * 检查是否安装微信
     *
     * @param context
     * @return
     */
    public static boolean checkAliApkExist(Context context) {
        String packageName = "com.eg.android.AlipayGphone";
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public static int getScreenWidth() {
        return getScreenSize().x;
    }

    public static Point getScreenSize() {
        Point point = new Point();
        WindowManager windowManager =
                (WindowManager) App.getContext().getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getSize(point);
        return point;
    }

    public static int getColor(int resId) {
        return getResource().getColor(resId);
    }


    public static void killProgress(Activity context) {
        context.finish();
        android.os.Process.killProcess(android.os.Process.myPid()); // 获取PID
        System.exit(0);
    }

    public static View getContentView(Activity activity) {
        try {
            if (activity == null || activity.isFinishing()) {
                return null;
            }
            Window window = activity.getWindow();
            if (window == null) {
                return null;
            }
            View decorView = window.getDecorView();
            if (decorView == null) {
                return null;
            }
            ViewGroup group = (ViewGroup) decorView.findViewById(android.R.id.content);
            if (group == null) {
                return null;
            }
            return group.getChildAt(0);
        } catch (Exception e) {
            e.printStackTrace();
            CrashReport.postCatchedException(e);
            return null;
        }
    }

    public static class imageInfo {
        private int width;
        private int height;

        public imageInfo(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }
    }

    public static void displayImage(final String url, final ImageView imageView) {
        if (StringUtils.isEmpty(url))
            return;

        GlideUtill.displayInterntImg(imageView.getContext(), url, imageView);
    }

    public static void displayImage(final Context context, final String url,
                                    final ImageView imageView) {
        if (StringUtils.isEmpty(url))
            return;
        imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {
                int width = imageView.getMeasuredWidth();
                int height = imageView.getMeasuredHeight();
                String imageurl = url;
                if (url.contains("?imageMogr2"))
                    imageurl = url.replace(url.substring(url.indexOf("?imageMogr2")), "");
                GlideUtill.displayInterntImg(context, imageurl, imageView);
                imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }

    public static void displayImage(final Context context, final String url,
                                    final ImageView imageView, int width, int height) {
        if (StringUtils.isEmpty(url))
            return;
        String imageurl = url;
        if (url.contains("?imageMogr2"))
            imageurl = url.replace(url.substring(url.indexOf("?imageMogr2")), "");
        GlideUtill.displayInterntImg(context, imageurl, imageView);
    }

    public static void displayRoundImage(final Context context, final String url,
                                         final ImageView imageView) {
        if (StringUtils.isEmpty(url))
            return;

        imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int width = imageView.getMeasuredWidth();
                int height = imageView.getMeasuredHeight();
                String imageurl = url;
                if (url.contains("?imageMogr2"))
                    imageurl = url.replace(url.substring(url.indexOf("?imageMogr2")), "");
//        if (url.startsWith("http"))
//          imageurl = imageurl + "?imageView2/2/w/" + width + "/h/" + height;
//        else {
//          imageurl = AppConstants.Global.http_iden + imageurl + "?imageView2/2/w/" + width + "/h/" + height;
//        }
//				F.j(imageurl);
//                Glide.with(imageView.getContext()).load(imageurl).diskCacheStrategy(DiskCacheStrategy.SOURCE).thumbnail(0.1f).into(imageView);
                Glide.with(context)
                        .load(imageurl).placeholder(R.mipmap.ic_xyb_logo_round) // 加载中
                        .error(R.mipmap.ic_xyb_logo_round) // 加载错误
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .thumbnail(0.1f)
                        .transform(new GlideRoundTransform(context, 4))
                        .into(imageView);
                imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

    }

    public static void displayImageLocal(final Context context, final String url,
                                         final ImageView imageView) {

        Glide.with(context)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .thumbnail(0.1f)
                .transform(new GlideRoundTransform(context, 4))
                .into(imageView);
    }

    public static void displayImage_noCache(Context context, String url, ImageView imageView) {
        Glide.with(context)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .signature(new StringSignature("01"))
                .skipMemoryCache(true)
                .thumbnail(0.1f)
                .into(imageView);
    }

    public static void displayRoundImage_noCache(Context context, String url, ImageView imageView) {
        Glide.with(context)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .signature(new StringSignature(System.currentTimeMillis() + ""))
                .skipMemoryCache(true)
                .thumbnail(0.1f)
                .transform(new GlideRoundTransform(context, 4))
                .into(imageView);
    }

    public static void displayCircleImage(Context context, String url, ImageView imageView) {
        if (XYBAUtils.checkContextNull(context))
            return;


        if (!StringUtils.isEmpty(url) && !url.startsWith("http")) {
            url = AppConstants.Global.http_iden + url;
        }

        Glide.with(context)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .signature(new StringSignature(UUID.randomUUID().toString()))
                .thumbnail(0.1f)
                .placeholder(R.mipmap.use_default_circle)
                .error(R.mipmap.use_default_circle)
                .skipMemoryCache(false)
                .transform(new GlideCircleTransform(context, 4))
                .into(imageView);
    }

    public static boolean isNotEmpty(Collection<?> collection) {
        return collection != null && collection.size() > 0;
    }

    public static boolean isEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }

    public static boolean isNotEmpty(Map<?, ?> map) {
        return !isEmpty(map);
    }

    /**
     * 获取指定尺寸图片
     */
    public static String image(String url, int width, int height) {
        if (url != null && url.endsWith("/null")) {
            return null;
        }
        if (width == 0 && height == 0) {
            return url;
        }
        return url + "?x-oss-process=image/resize,w_" + width + ",h_" + height;
    }

    public static void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 获取指定尺寸正方形图片
     */
    public static String image(String url, int size) {

        return image(url, size, size);
    }

    public static boolean isEmpty(Collection<?> collection) {
        return !isNotEmpty(collection);
    }

    private static final NumberFormat PRICE_FORMAT = NumberFormat.getCurrencyInstance(Locale.CHINA);

    public static String formatPrice(Double price) {
        return PRICE_FORMAT.format(price);
    }

    public static String formatDouble(Double price) {
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(price);
    }

    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 价格前面加人民币符号
     */
    public static String formatPrice(String price) {
        if (StringUtils.isEmpty(price) || price.equals("null") || price.equals("NULL"))
            return "";
        Double dbvalue = null;
        try {
            dbvalue = Double.parseDouble(price);
        } catch (Exception e) {
            return "";
        }
        return formatPrice(dbvalue);
    }

    public static String join(final Iterable<?> iterable, final String separator) {
        if (iterable == null) {
            return null;
        }
        return join(iterable.iterator(), separator);
    }

    public static final String EMPTY = "";

    public static String join(final Iterator<?> iterator, final String separator) {

        // handle null, zero and one elements before building a buffer
        if (iterator == null) {
            return null;
        }
        if (!iterator.hasNext()) {
            return EMPTY;
        }
        final Object first = iterator.next();
        if (!iterator.hasNext()) {
            final String result = toString(first);
            return result;
        }

        // two or more elements
        final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
        if (first != null) {
            buf.append(first);
        }

        while (iterator.hasNext()) {
            if (separator != null) {
                buf.append(separator);
            }
            final Object obj = iterator.next();
            if (obj != null) {
                buf.append(obj);
            }
        }
        return buf.toString();
    }

    public static String toString(Object obj) {
        return obj == null ? "" : obj.toString();
    }

    /**
     * 把Runnable 方法提交到主线程运行
     * @param runnable
     */
    //    public static void runOnUiThread(Runnable runnable) {
    //        // 在主线程运行
    //        if(android.os.Process.myTid() == App.getMainTid()){
    //            runnable.run();
    //        }else{
    //            //获取handler
    //            App.getHandler().post(runnable);
    //        }
    //    }

    /**
     * 判断用户是否登录
     */
    public static boolean hasLogin() {
        Long userId = 0l;//Preferences.getDefault().getLong(AppConstants.LOGIN_USER_ID_KEY, 0);
        return userId > 0;
    }

    public static Field LISTENER_INFO_OF_VIEW, LISTENER_OF_CLICK;

    public static void forceLogin(View view, List<Integer> viewIds) {
        for (int viewId : viewIds) {
            forceLogin(view.findViewById(viewId));
        }
    }

    public static void forceLogin(Activity activity, List<Integer> viewIds) {
        for (int viewId : viewIds) {
            forceLogin(activity.findViewById(viewId));
        }
    }

    public static void forceLogin(Activity activity, Integer... viewIds) {
        for (int viewId : viewIds) {
            forceLogin(activity.findViewById(viewId));
        }
    }

    /**
     * 使用新的listener代理原来的listener,实现统一判断是否登录
     */
    public static void forceLogin(View... views) {
        if (LISTENER_INFO_OF_VIEW == null) {
            LISTENER_INFO_OF_VIEW = ReflectUtils.getField(View.class, "mListenerInfo");
        }
        for (View view : views) {
            Object listenerInfo = ReflectUtils.get(LISTENER_INFO_OF_VIEW, view);
            if (LISTENER_OF_CLICK == null) {
                LISTENER_OF_CLICK = ReflectUtils.getField(listenerInfo.getClass(), "mOnClickListener");
            }
            View.OnClickListener listener = ReflectUtils.get(LISTENER_OF_CLICK, listenerInfo);
            if (listener == null) {
                throw new RuntimeException("View还没有定义点击事件");
            }
            view.setOnClickListener(new OnClickListenerForceLogin(view, listener));
        }
    }

    static final Map<Class<?>, Constructor<?>> BINDINGS = new LinkedHashMap<>();

    public static void bind(Object target) {
        createBinding(target);
    }

    //    public <T extends BaseView,E extends BaseModule> void bind_1(T view,E module){//注入
    //
    //        App.getApp().getAppComponent().plus(module).
    //    }
    private static void createBinding(Object target) {
        Class<?> targetClass = target.getClass();
        Constructor<?> constructor = findBindingConstructorForClass(targetClass);

        if (constructor == null) {
            return;
        }

        //noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
        ReflectUtils.newInstance(constructor, target);
    }

    private static Constructor<?> findBindingConstructorForClass(Class<?> cls) {
        Constructor<?> bindingConstructor = BINDINGS.get(cls);
        if (bindingConstructor != null) {
            return bindingConstructor;
        }
        String clsName = cls.getCanonicalName();
        if (clsName.startsWith("android.") || clsName.startsWith("java.")) {
            return null;
        }
        try {
            Class<?> bindingClass = Class.forName(clsName + "_AppBinding");
            //noinspection unchecked
            bindingConstructor = bindingClass.getConstructor(cls);
        } catch (ClassNotFoundException e) {
            bindingConstructor = findBindingConstructorForClass(cls.getSuperclass());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Unable to find binding constructor for " + clsName, e);
        }
        BINDINGS.put(cls, bindingConstructor);
        return bindingConstructor;
    }

    public static void toast(String message) {
        Toast.makeText(App.getContext(), message, Toast.LENGTH_SHORT).show();
    }

    public static int getWindowWidth() {
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getWidth();
    }

    public static int getWindowHeight() {
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getHeight();
    }

    public static void showShortToast(String text) {
        ToastView toastView = new ToastView(getContext(), text);
        toastView.setGravity(Gravity.CENTER, 0, 0);
        toastView.show();
    }

    public static void deepCopy(Object src, Object dest, boolean careingore) {
        Field[] field = src.getClass().getDeclaredFields(); // 获取实体类的所有属性，返回Field数组
        for (int j = 0; j < field.length; j++) { // 遍历所有属性
            try {
                if (careingore && null != field[j].getAnnotation(IngoreCopy.class)) {
                    continue;
                }
                String name = field[j].getName(); // 获取属性的名字
                name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set方法
                String type = field[j].getGenericType().toString(); // 获取属性的类型

                if (type.equals("class java.lang.String")) { // 如果type是类类型，则前面包含"class "，后面跟类名
                    Method m = src.getClass().getMethod("get" + name);
                    String value = (String) m.invoke(src); // 调用getter方法获取属性值
                    m = dest.getClass().getMethod("set" + name, String.class);
                    if (value == null) {
                        m.invoke(dest, "");
                    } else {
                        m.invoke(dest, value);
                    }
                } else if (type.equals("class java.lang.Integer")) {
                    Method m = src.getClass().getMethod("get" + name);
                    Integer value = (Integer) m.invoke(src);
                    m = dest.getClass().getMethod("set" + name, Integer.class);
                    if (value == null) {
                        m.invoke(dest, 0);
                    } else {
                        m.invoke(dest, value);
                    }
                } else if (type.equals("class java.lang.Double")) {
                    Method m = src.getClass().getMethod("get" + name);
                    Double value = (Double) m.invoke(src);
                    m = dest.getClass().getMethod("set" + name, Double.class);
                    if (value == null) {
                        m.invoke(dest, new Double(0f));
                    } else {
                        m.invoke(dest, value);
                    }
                } else if (type.equals("class java.lang.Long")) {
                    Method m = src.getClass().getMethod("get" + name);
                    Long value = (Long) m.invoke(src);
                    m = dest.getClass().getMethod("set" + name, Long.class);
                    if (value == null) {
                        m.invoke(dest, new Long(0l));
                    } else {
                        m.invoke(dest, value);
                    }
                } else if (type.equals("class java.lang.Boolean")) {
                    Method m = src.getClass().getMethod("get" + name);
                    Boolean value = (Boolean) m.invoke(src);
                    m = dest.getClass().getMethod("set" + name, Boolean.class);
                    if (value == null) {
                        m.invoke(dest, false);
                    } else {
                        m.invoke(dest, m);
                    }
                } else if (type.equals("class java.util.Date")) {
                    Method m = src.getClass().getMethod("get" + name);
                    Date value = (Date) m.invoke(src);
                    m = dest.getClass().getMethod("set" + name, Date.class);
                    if (value == null) {
                        m.invoke(dest, new Date());
                    } else {
                        m.invoke(dest, value);
                    }
                } else {
                    field[j].setAccessible(true);//暴力访问，取消age的私有权限。让对象可以访问
                    Method m1 = src.getClass().getMethod("get" + name);
                    Object value = m1.invoke(src);
                    if (null == value) {
                        continue;
                    }
                    Method m2 = dest.getClass().getMethod("set" + name, value.getClass());
                    m2.invoke(dest, value);
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    public static String paraseURL(String url) {
        if (url.contains("kachemama://") && !url.contains("kachemama://kachemama")) {
            url = url.replace("kachemama://", "kachemama://kachemama/");
        }
        if (!url.contains("kachemama://") && !url.startsWith("/")) {
            url = "/kachemama/" + url;
        }
        return url;
    }

    public static void gotoURL(String url) {
        if (!StringUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            String group = uri.getQueryParameter("group");
            Set<String> paramkeys = uri.getQueryParameterNames();
            Bundle bundle = new Bundle();
            for (String str : paramkeys) {
                bundle.putString(str, uri.getQueryParameter(str));
            }
            if (StringUtils.isEmpty(group)) {
                ARouter.getInstance().build(uri).navigation();
            } else {
                ARouter.getInstance().build(uri.getPath(), group).with(bundle).navigation();
            }
        }
    }

    public static boolean checkContextNull(Context context) {
        try {
            if (context == null || ((Activity) context).isFinishing()) {
                return true;
            }
        } catch (Exception e) {
            return true;
        }
        return false;
    }

    public static void converJavaBean(Object class1, Object class2) {
        try {
            Class<?> clazz1 = class1.getClass();
            Class<?> clazz2 = class2.getClass();
            // 得到method方法
            Method[] method1 = clazz1.getMethods();
            Method[] method2 = clazz2.getMethods();

            int length1 = method1.length;
            int length2 = method2.length;
            if (length1 != 0 && length2 != 0) {
                // 创建一个get方法数组，专门存放class2的get方法。
                Method[] get = new Method[length2];
                for (int i = 0, j = 0; i < length2; i++) {
                    if (method2[i].getName().indexOf("get") == 0) {
                        get[j] = method2[i];
                        ++j;
                    }
                }

                for (int i = 0; i < get.length; i++) {
                    if (get[i] == null)// 数组初始化的长度多于get方法，所以数组后面的部分是null
                        continue;
                    // 得到get方法的值，判断时候为null，如果为null则进行下一个循环
                    Object value = get[i].invoke(class2, new Object[]{});
                    if (null == value)
                        continue;
                    // 得到get方法的名称 例如：getXxxx
                    String getName = get[i].getName();
                    // 得到set方法的时候传入的参数类型，就是get方法的返回类型
                    Class<?> paramType = get[i].getReturnType();
                    Method getMethod = null;
                    try {
                        // 判断在class1中时候有class2中的get方法，如果没有则抛异常继续循环
                        getMethod = clazz1.getMethod(getName, new Class[]{});
                    } catch (NoSuchMethodException e) {
                        continue;
                    }
                    // class1的get方法不为空并且class1中get方法得到的值为空，进行赋值，如果class1属性原来有值，则跳过
                    if (null == getMethod || null != getMethod.invoke(class1, new Object[]{}))
                        continue;
                    // 通过getName 例如getXxxx 截取后得到Xxxx，然后在前面加上set，就组装成set的方法名
                    String setName = "set" + getName.substring(3);
                    // 得到class1的set方法，并调用
                    Method setMethod = clazz1.getMethod(setName, paramType);
                    setMethod.invoke(class1, value);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static ArrayList<String> getBrowserHistory(Context context) {
        ArrayList<String> browserHistory = new ArrayList<String>();
        try {
            ContentResolver contentResolver = context.getContentResolver();
            Cursor cursor = contentResolver.query(Uri.parse("content://browser/bookmarks"),
                    new String[]{"title", "url", "date"}, "date!=?",
                    null, "date desc");
            SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");
            Date date;
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    date = new Date(cursor.getLong(cursor.getColumnIndex("date")));
                    String title = cursor.getString(cursor.getColumnIndex("title"));
                    String url = cursor.getString(cursor.getColumnIndex("url"));
                    String browserhistory = sfd.format(date) + ";" + title + ";" + url;
                    F.j(browserhistory);
                    browserHistory.add(browserhistory);
                }
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return browserHistory;
    }

    public static void hideInputSoft(Context context, EditText editText) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }
}
